#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "./openblas-0.3.18.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

if [[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]]; then
    echo "请输入正确的构建路径"
    exit 1
fi
if [[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]]; then
    echo "请输入正确的安装路径"
    exit 1
fi
get_openblas(){
    cnt=1
    number=10
    while [ $cnt -lt $number ]
    do
        set +e
        echo "正在下载openblas,时间较长,请耐心等待......"
        wget -c -P "$buildpath" https://github.com/xianyi/OpenBLAS/releases/download/v0.3.18/OpenBLAS-0.3.18.tar.gz
        result_code=$?
        if [ $result_code -ne 0 ];then
            cnt=$((cnt+1))
        else
            echo "下载openblas成功"
            break
        fi
    done
    if [ $cnt -eq $number ];then
        echo "下载openblas失败,请重新执行脚本"
        exit
    fi
    set -e
}
buildpath=$1
installpath=$2
if [[ "$1" =~ .*/$ ]]; then buildpath=${buildpath%/*}; fi
if [[ "$2" =~ .*/$ ]]; then installpath=${installpath%/*}; fi
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e 
yum install -y wget tar cmake environment-modules --nogpgcheck
get_openblas
tar xf "$buildpath"/OpenBLAS-0.3.18.tar.gz -C "$buildpath" && rm -rf "$buildpath"/OpenBLAS-0.3.18.tar.gz
cd "$buildpath"/OpenBLAS-0.3.18 || exit

CC=clang CXX=clang++ FC=flang \
    make -j$(nproc) && make -j$(nproc) PREFIX="$installpath"/openblas install

cat >"$installpath/openblas/OpenBLAS-0.3.18_modulefiles" <<EOF
#%Module1.0
conflict OpenBLAS
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set OpenBLAS \$pwd
setenv OpenBLAS \$OpenBLAS
prepend-path LD_LIBRARY_PATH \$OpenBLAS/lib
EOF

rm -rf "$buildpath"/OpenBLAS-0.3.18
